#!/usr/bin/env bash

# An installation script for openbox-config.

# Fix path whether run by repo root install.sh symlink or script file
cd "$(dirname $0)" && cd scripts &>/dev/null
source "inc/common.sh"

show_message '' $MESSAGE_TYPES[warning]
show_message " >  WARNING! This script is under development and may not work as expected." $MESSAGE_TYPES[warning]
show_message " >  This can potentially break your system! Use at your own risk!" $MESSAGE_TYPES[warning]
show_message " >  To avoid risk please press Ctrl+C to quit out of it." $MESSAGE_TYPES[warning]
show_message '' $MESSAGE_TYPES[warning]

# Reset cache so that it can be updated, in case package list changed
rm "${ENV_INFO[search_cache_installed]}" 2>/dev/null
rm "${ENV_INFO[search_cache_available]}" 2>/dev/null

# Gather missing programs/packages that need to be installed
missing_programs=$(get_missing_programs)

# We need Python Pip for dotdrop
if [ "$(is_binary_installed "pip")" = "$FALSE" ] && [ "$(is_binary_installed "pip3")" = "$FALSE" ]; then
	if [ "$(is_package_available "python3-pip")" = "$TRUE" ]; then
		missing_programs+=' python3-pip'
	elif [ "$(is_package_available "python-pip")" = "$TRUE" ]; then
		missing_programs+=' python-pip'
	elif [ "$(is_package_available "pip" "py[0-9][0-9]-pip")" = "$TRUE" ]; then # FreeBSD
		missing_programs+=' '$(package_search "pip" | sed -ne 's|^\(py[0-9][0-9]-pip\)$|\1|p')
	elif [ "$(is_package_available "py3-pip")" = "$TRUE" ]; then # OpenBSD
		missing_programs+=' py3-pip'
	elif [ "${ENV_INFO[package_manager]}" = "apk" ]; then # Alpine
		show_message "Enabling community repo if not enabled already..." $MESSAGE_TYPES[action]
		$subin sed -i'.bak' 's|#\(.*[0-9]\/community\)|\1|' /etc/apk/repositories
		$subin apk update
		if [ "$(is_package_available "py3-pip")" = "$TRUE" ]; then
			missing_programs+=' py3-pip'
		else
			missing_programs+=' python3'
		fi
	else
		show_message "Error: Python Pip package name cannot be determined for your system. Please install manually." $MESSAGE_TYPES[error]; exit 34762
	fi
fi
# dotdrop needs 'file' package (in case it is not installed, such as in Alpine)
if [ "$(is_binary_installed file)" = "$FALSE" ]; then
	missing_programs+=' file'
fi
# To fix mouse cursor not moving after login
if [ "$(is_package_installed xf86-input-evdev)" = "$FALSE" ]; then
	missing_programs+=' xf86-input-evdev'
fi
# install xorg-server if not installed
if [ "$(is_binary_installed "X")" = "$FALSE" ]; then
	if [ "${ENV_INFO[operating_system_name]}" = 'alpine' ]; then
		$subin setup-xorg-base
	else
		missing_programs+=' xorg-server'
		# Install xf86 drivers for intel built in graphics
		if [ ! -z "$(cat /proc/cpuinfo | grep -i 'vendor_id.*Intel')" ]; then
			missing_programs+=' xf86-video-intel'
		fi
		show_message 'Xorg was not found on the system and it will be installed, but depending on your system you may have to do other things to make it work.' $MESSAGE_TYPE[warning]
	fi
fi

# Install icon package if needed
if [ -d "/usr/share/icons/Papirus/" ] || [ -d "/usr/local/share/icons/Papirus/" ] || [ -d "$HOME/.icons/Papirus/" ]; then
	show_message 'Papirus icon theme is installed... Skipping install.' $MESSAGE_TYPES[info]
else
	if [ "$(is_package_available "papirus-icon-theme")" = "$TRUE" ]; then
		missing_programs+=' papirus-icon-theme'
	else
		show_message 'Error: Papirus icon theme package not found. Install papirus icon theme manually.' $MESSAGE_TYPES[error]
	fi
fi

# Install font package if there are no fonts installed by default (e.g. on Alpine.)
# There has to be some font, otherwise it shows boxes in place of text.
fc-list | grep .ttf &>/dev/null
if [ "$?" -gt "0" ]; then
	missing_programs+=' ttf-dejavu'
fi

show_message "Found missing programs: $missing_programs" $MESSAGE_TYPES[info]
show_message 'Will attempt to install them...' $MESSAGE_TYPES[action]

# Install the missing packages
install_packages "$missing_programs"

# To help detect userspace installation
export PATH="$PATH:$HOME/.local/bin/"
# Install dotdrop
if [ "$(is_binary_installed "dotdrop")" = "$FALSE" ]; then 
	if [ "$(is_binary_installed "pip")" = "$TRUE" ]; then
		pip_bin=pip
	elif [ "$(is_binary_installed "pip3")" = "$TRUE" ]; then
		pip_bin=pip3
	elif [ -n "$(ls /usr/local/bin/pip3*)" ]; then # OpenBSD
		pip_bin=$(ls /usr/local/bin/pip3* | head -n 1)
	else
		show_message 'Error: Python Pip is not installed. Please install and continue. Exiting...' $MESSAGE_TYPES[fatal]; exit 56928
	fi
	$pip_bin install dotdrop
fi
# Make sure dotdrop binary is accessible
if [ "$(is_binary_installed "dotdrop")" = "$FALSE" ]; then 
	show_message 'Error: dotdrop cannot be executed. Unfortunately cannot continue. Exiting...' $MESSAGE_TYPES[fatal]; exit 28492
elif [ -f "$HOME/.local/bin/dotdrop" ]; then
	dotdrop_bin="$HOME/.local/bin/dotdrop"
else
	dotdrop_bin=dotdrop
fi

# Dotdrop's BSD bug workaround
# There is a bug that even if there are ./custom.yaml and ~/.local/share/openbox-config/custom.yaml, they are not read and respected. Only the first file is read for variables. This happens only in BSD platforms (confirmed on freebsd and openbsd). This is a workaround to fix this. One of the conditions is that, there should be *all* keys present in the custom.yaml.
if [ "${ENV_INFO[operating_system_name]}" = 'freebsd' ] || [ "${ENV_INFO[operating_system_name]}" = 'openbsd' ]; then
	# Setting the preferred file
	if [ -f "${HOME}/.local/share/openbox-config/custom.yaml" ]; then
		pref_custom_file="$(realpath ~/.local/share/openbox-config/custom.yaml)"
	elif [ -f "../custom.yaml" ]; then
		pref_custom_file="$(realpath ../custom.yaml)"
	fi
	if [ -n "$pref_custom_file" ]; then
		# Create a temp dir to contain everything
		tmpdir=`mktemp -d -t openbox-config.XXXXXX`
		mkdir -p "$tmpdir"
		show_message "BSD environment detected. Will be creating workaround files in ${tmpdir}. This might fail if not *all* variables are found in ${pref_custom_file} file." $MESSAGE_TYPES[info]
		# Save temp file paths
		tmpconfigfile="${tmpdir}/config.yaml"
		cp -f ../config.yaml "${tmpdir}/"
		sed -i'.bak' "s|- custom.default.yaml$|- ${pref_custom_file}|" "$tmpconfigfile"
		# Place in repo root to maintain so that dotdrop can find paths
		cp "$tmpconfigfile" ../temp_custom.yaml
		# Add options to use temp custom file instead of default config.yaml
		dotdrop_extra_params="-ctemp_custom.yaml"
	fi
fi
# To clean leftover temp files
function clean_temp_custom_yaml {
	if [ -n "$tmpconfigfile" ]; then
		show_message 'Removing BSD workaround files...' $MESSAGE_TYPES[info]
		rm ../temp_custom.yaml
	fi
}

# Continue rest of the installation

show_message "There are ${#CONFIG_VARIATIONS[@]} variations available:" $MESSAGE_TYPES[info]
for i in "${!CONFIG_VARIATIONS[@]}"; do
	echo "      ${i} ${CONFIG_VARIATIONS[$i]}"
done
show_message 'Please enter the corresponding number to choose [Default is 1]: ' $MESSAGE_TYPES[info] -n
read variation_input
if [[ ! "$variation_input" =~ ^[0-9]+$ ]] || ( [ "$variation_input" -lt "1" ] || [ "$variation_input" -gt "${#CONFIG_VARIATIONS[@]}" ] ); then
	variation_input=1
fi
variation="${CONFIG_VARIATIONS[${variation_input}]}"
show_message "'$variation' variation is chosen." $MESSAGE_TYPES[info]
show_message 'Now proceeding to install...' $MESSAGE_TYPES[action]

show_message "Are you sure you want to install '$variation' variation of the config [y/N]? " $MESSAGE_TYPES[info] -n
read sure_input
if [ "$(get_user_confirm $sure_input NO)" = "YES" ]; then
	cd ..
	$dotdrop_bin install -p "$variation" -f "$dotdrop_extra_params"
	cd scripts
	clean_temp_custom_yaml

	show_message 'Changing icon theme...' $MESSAGE_TYPES[action]
	if [ "$variation" = 'default' ]; then
		$REPO_ROOT/scripts/changeicon.sh Papirus
	elif [ "$variation" = 'dark' ]; then
		$REPO_ROOT/scripts/changeicon.sh Papirus-Dark
	fi

	# Only restart if on an openbox session
	if [ "$(is_process_running openbox)" = "$TRUE" ]; then
		show_message 'Restarting openbox and tint2 to apply changes...' $MESSAGE_TYPES[action]
		openbox --reconfigure
		[ "$(is_process_running tint2)" = "$TRUE" ] && kill -15 "$(get_process_id tint2)"
		# So that file manager doesn't open on $PWD after restart
		cd "$HOME"
		tint2 &>/dev/null && disown &
	else
		# Check if ~/.xinitrc exists and already has exec openbox-session line (by discarding commented lines first).
		# If not, ask to create one which starts openbox session.
		if ! sed -e '/^[[:space:]]*#.*/d' "$HOME/.xinitrc" | grep 'exec.*openbox-session' &>/dev/null; then
			show_message "This will automatically create a file so that you can start openbox session when you run 'startx' from tty. Enter yes if you boot into a text based tty and you don't have a Display Manager (like gdm, lightdm, xdm etc.) setup on the system. Do you want to create a ~/.xinitrc automatically [y/N]? " $MESSAGE_TYPES[info] -n
			read sure_input
			if [ "$(get_user_confirm $sure_input NO)" = "YES" ]; then
				$REPO_ROOT/scripts/autoxinitrc.sh
			fi
		fi
		show_message 'Currently not running an Openbox session. Please logout or restart and login into an Openbox session.'  $MESSAGE_TYPES[warning]
	fi
else
	clean_temp_custom_yaml
	show_message 'Chosen to abort. Exiting...' $MESSAGE_TYPES[fatal]; exit 34918
fi
